<template>
  <div class="app-wrapper">
    <headerTitle :titleList="titleList" :hideButton="true" />
    <div class="app-container">
      <div class="block containerMain" ref="block">
        <div class="tab-container">
          <div class="con-title">账号基本信息</div>
          <el-form
            style="width:78%;margin-left: 60px;"
            ref="ruleForm1"
            :model="infoForm"
            :rules="formrules"
            label-width="80px"
            autocomplete="off"
          >
            <el-form-item label="登录账号" prop="username">
              <div class="elform-item">
                <el-input class="item" size="small" placeholder="请输入登录账号" v-model="infoForm.username" :disabled="!addRelated||!viewShow"></el-input>
                <span v-if="viewShow" class="item-span">4-20位字符，可由数字字母组成，字母区分大小写</span>
              </div>
            </el-form-item>
           <el-form-item label="账号昵称" prop="realname">
             <el-input
               style="width: 40%"
               size="small"
               maxlength="16"
               :disabled="!viewShow"
               placeholder="请输入帐号昵称"
               v-model="infoForm.realname"
             ></el-input>
           </el-form-item>

            <el-form-item label="账号权限" prop="roleId">
              <el-select
                  style="width: 40%"
                  size="small"
                  :disabled="!viewShow"
                  v-model="infoForm.roleId"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in accountList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  >{{ item.name }}</el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="账号密码" prop="password" v-show="addRelated&&viewShow">
              <div class="elform-item">
                <el-input type="password" class="item" size="small" @input = "infoForm.password=infoForm.password.replace(/[^0-9a-zA-Z]/g,'')" placeholder="请输入密码" v-model="infoForm.password"></el-input>
                <span class="item-span">6-16位字符，可由数字字母组成，字母区分大小写</span>
              </div>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword" v-show="addRelated&&viewShow">
              <div class="elform-item">
                <el-input type="password" class="item" size="small" @input = "infoForm.confirmPassword=infoForm.confirmPassword.replace(/[^0-9a-zA-Z]/g,'')" placeholder="请输入密码" v-model="infoForm.confirmPassword"></el-input>
                <span class="item-span">6-16位字符，可由数字字母组成，字母区分大小写</span>
              </div>
            </el-form-item>
          </el-form>

          <div style="width:78%; margin-left:70px;">
            <el-button size="mini" v-if="type=='2'" type="default" @click="cancel()">返回</el-button>
            <el-button size="mini" v-else type="default" @click="cancel()">取消</el-button>
            <el-button size="mini" type="primary" v-if="viewShow" @click="saveAdd()">保存</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import MD5 from 'js-md5'
import HeaderTitle from "@/components/Headertitle/index";
import { fetchOrganList, fetchAccount, fetchAdd, fetchGetData, fetchEdit, fetchSkillgroup, fetchCcod } from "@/api/systemapi/user";
import { translateDataToTree } from "@/utils";
export default {
  components: {
    HeaderTitle
  },
  data() {
    var checkusername = (rule, value, callback) => {
      var res = /^[a-zA-Z0-9]/
      if (!value) {
        return callback(new Error('登陆账号不能为空'));
      } else if(!res.test(value)) {
        return callback(new Error('登陆账号不合规格，请重新输入'));
      } else {
        return callback();
      }
    };
    var checkPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('确认密码不能为空'));
      } else if(value != this.infoForm.password) {
        return callback(new Error('两次密码输入不一致'));
      } else {
        return callback();
      }
    };
    var checkuserPhone = (rule, value, callback) => {
      var res = /^1[3456789]\d{9}$/
      if (!value) {
        return callback();
      } else if(!res.test(value)) {
        return callback(new Error('手机号码不合规格，请重新输入'));
      } else {
        return callback();
      }
    };
    var checkEmail = (rule, value, callback) => {
      var res = /@/
      if (!value) {
        return callback();
      } else if(!res.test(value)) {
        return callback(new Error('邮箱不合规格，请重新输入'));
      } else {
        return callback();
      }
    };
    return {
      entNum:"",
      titleList: [{ title: "账号管理" }, { title: "新增账号" }],
      organprops: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true
      },
      type: "", //查看编辑新增
      addRelated: true, // add相关控件隐藏显示
      viewShow: true, // 查看展示
      editid: "", // id
      treeData: null,
      infoForm: {
        username: "",// 登陆账号
        realname: "",// 账号昵称
        organId: "",// 所属机构id
        roleId: "",// 账号权限id
        skillGroupId: "",// 技能组权限
        password: "", // 密码
        confirmPassword: "", // 确认密码
        phone: "", // 手机号码
        telephone: "",// 固话
        email: "", // 邮箱地址
        inspectType: 1,//
      },
      accountList: [],// 账号权限下拉数组
      groupList: [],// 技能组
      addrules: {
        username: [
          { required: true, validator: checkusername, trigger: 'blur' },
          { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
        ],
        organId: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        roleId: [
          { required: true, message: '请选择账号权限', trigger: 'change' }
        ],
        // skillGroupId: [
        //   { required: true, message: '请选择技能组权限', trigger: 'change' }
        // ],
        password: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: checkPassword, trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        phone: [
          { validator: checkuserPhone, trigger: 'blur' },
          { min: 11, max: 13, message: '长度在 11 到 13 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      editrules: {
        roleId: [
          { required: true, message: '请选择账号权限', trigger: 'change' }
        ],
        phone: [
          { validator: checkuserPhone, trigger: 'blur' },
          { min: 11, max: 13, message: '长度在 11 到 13 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      ccodShow: false,
      zsAudioStatus: "",
    };
  },
  mounted() {
    const { entNum } = this.$route.query;
    this.entNum = entNum;
    this.zsAudioStatus = this.$route.query.zsAudioStatus;
    this.type = this.$route.query.type;
    if(this.type=='1'){
      this.titleList[1].title='编辑账号';
      this.addRelated = false;
      this.editid = this.$route.query.id;
      this.getEditData(this.$route.query.id);
    }
    if(this.type=='2'){
      this.titleList[1].title='查看账号';
      this.viewShow = false;
      this.getEditData(this.$route.query.id);
    }
    // this.getOrganList();
    this.getAccount();
   // this.getSkillgroup();
    //this.getCcod();
  },
  computed: {
    formrules: function() {
      if (this.type=='1') {
        return this.editrules;
      } else {
        return this.addrules;
      }
    }
  },
  methods: {
    cancel() {
      this.$router.push({
        name: "userView",
        params: { entNum: this.entNum }
      });
    },
    // 账号权限下拉
    getAccount() {
      fetchAccount(this.entNum).then(res => {
        this.accountList = res.data;
        console.log(this.accountList)
      })
    },
    getEditData(id) {
      fetchGetData({id: id}).then(res => {
        this.infoForm = res.data;
      })
    },
    saveAdd() {
      const p1=new Promise((resolve,reject)=>{
        this.$refs['ruleForm1'].validate(valid=>{
            if(valid) {
              resolve()
            } else {
              console.log('error submit!!');
              return false;
            }
        })
      })
      // const p2=new Promise((resolve,reject)=>{
      //   this.$refs['ruleForm2'].validate(valid=>{
      //       if(valid) {
      //         resolve()
      //       } else {
      //         console.log('error submit!!');
      //         return false;
      //       }
      //   })
      // })
      Promise.all([p1]).then(()=>{
        console.log('验证通过,提交表单')
        if(this.type=='1'){
          fetchEdit(
            {
              id: this.editid,
              entNum:this.entNum,
              username: this.infoForm.userName,// 登陆账号
              realname: this.infoForm.realname,// 账号昵称
              roleId: this.infoForm.roleId// 账号权限id
             }
            ).then(response => {
            if (response.code == 0) {
              this.cancel();
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          });
        } else {
          this.infoForm.organId=this.infoForm.organId[this.infoForm.organId.length-1];
          fetchAdd({ ...this.detailForm,entNum:this.entNum, ...this.infoForm, password:MD5(this.infoForm.password),originalPassword:this.infoForm.password,confirmPassword:MD5(this.infoForm.confirmPassword)}).then(response => {
            if (response.code == 0) {
              this.cancel();
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          });
        }
      })
    },
  }
};
</script>
<style lang="scss" scoped>
.app-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  .app-container {
    .block {
      width: 100%;
      height: 100%;
      background: #fff;
      .tab-container {
        width: 100%;
        margin-top: 15px;
        .con-title {
          margin-bottom: 15px;
          font-size: 14px;
          color: #666;
          font-weight: bold;
          margin-left: 10px;
        }
        .elform-item {
          display: flex;
          .item {
            width: 40%;
            margin-right: 20px;
          }
          .item-span {
            color: #ccc;
            font-size: 13px;
          }
        }
      }
    }
  }
}
</style>
